package com.example.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC工具类，使用Druid连接池
 */
public class JDBCUtils {
    //数据源
    private static DataSource ds;

    static {
        //加载配置文件
        try {
            Properties properties = new Properties();
            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            InputStream stream = classLoader.getResourceAsStream("druid.properties");
            properties.load(stream);
            //初始化数据源
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Connection对象
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConn() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 获取连接池对象
     *
     * @return
     */
    public static DataSource getDataSource() {
        return ds;
    }

}
